/**
 * Created by WangMing on 15/12/9.
 */
define(["../../service",
    "../../../src/assets/vendor/oniui/dialog/avalon.dialog",
    "../../assets/vendor/bootstrap/bootstrap-dropdown",
    "../../assets/vendor/jquery-ui-1.11.4.min",
    "../../assets/vendor/datatimepicker-language"
], function(api) {
    function MobileClient() {
        //以下是判断是否在移动客户端
        var sUserAgent = navigator.userAgent.toLowerCase();
        var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
        var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
        var bIsAndroid = sUserAgent.match(/android/i) == "android";
        if (bIsIpad || bIsIphoneOs || bIsAndroid) {
            return true;
        }
        return false;
    }
    function getCookie(name)
    {  
        var nameEQ = name + "=";  
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) 
        {  
            var c = ca[i];  
            while(c.charAt(0)==' ')
            {
                c = c.substring(1,c.length);
            }
            if(c.indexOf(nameEQ) == 0) 
            {
                return unescape(c.substring(nameEQ.length,c.length));
            }
        }
        return false;  
    }

    function clearCookie(name)

    {  
        setCookie(name, "", -1);
    }

    function setCookie(name, value, seconds){  
        seconds = seconds || 0;  
        var expires = "";
        if(seconds != 0 ){
            var date = new Date();
            date.setTime(date.getTime()+(seconds*1000));  
            expires = ";expires="+date.toGMTString();
        }  
        document.cookie = name+"="+escape(value)+expires+";path=/";
    }

    // 定义所有相关的vmodel
    var vm = avalon.define({
        $id: "liveRegister",
        $setting:{},
        gradeSection: [],
        categorySection: [],
        timeList: [],
        logon:'',
        equipmentList:[],
        nickname:'',
        selectDayIsWeekend:false,
        title: '',
        speaker: '',
        parentGrade: '',
        parentCategory: '',
        viewPassword: '',
        zgbm: '',
        date:new Date().getFullYear()+'-'+(new Date().getMonth()+1)+'-'+new Date().getDate(),
        chapterselect: {},
        equipment:' ',
        equipmentDefault : false,

        uri:'',
        registering:false,

        livedialogID : "",

        selectChatper: function(el,obj) {
            vm[obj] = el;
        },
        showDialog:function(id){

            if(!MobileClient()){
                document.getElementById("iframe").setAttribute("src","http://pt.ava.com.cn/qq/authorize.jsp?receive=liveRegister&extra="+location.origin+"/open/qq/receive.html&title="+encodeURIComponent($('input[name="title"]').val())+"&speaker="+encodeURIComponent($('input[name="speaker"]').val()) +"&parentRecordEquipment="+encodeURIComponent(vm.equipment)+"&date="+encodeURIComponent($('#date').val())+"&chapter="+encodeURIComponent($('input[name="chapter"]').val())+"&startTime="+encodeURIComponent($('#startTime').val())+"&endTime="+encodeURIComponent($('#endTime').val())+"&parentGrade="+encodeURIComponent(vm.parentGrade)+"&parentCategory="+encodeURIComponent(vm.parentCategory)+"&viewPassword="+encodeURIComponent(vm.viewPassword));
            }
            else{
                location.href = "http://pt.ava.com.cn/qq/authorize.jsp?receive=liveRegister&extra="+location.origin+"/open/qq/receive.html&title="+encodeURIComponent($('input[name="title"]').val())+"&speaker="+encodeURIComponent($('input[name="speaker"]').val()) +"&parentRecordEquipment="+encodeURIComponent(vm.equipment)+"&date="+encodeURIComponent($('#date').val())+"&chapter="+encodeURIComponent($('input[name="chapter"]').val())+"&startTime="+encodeURIComponent($('#startTime').val())+"&endTime="+encodeURIComponent($('#endTime').val())+"&parentGrade="+encodeURIComponent(vm.parentGrade)+"&parentCategory="+encodeURIComponent(vm.parentCategory)+"&viewPassword="+encodeURIComponent(vm.viewPassword)
            }
            //console.log("http://pt.ava.com.cn/qq/authorize.jsp?extra="+location.origin+"/open/qq/receive.html&title="+$('input[name="title"]').val()+"&speaker="+ $('input[name="speaker"]').val()+"&parentRecordEquipment="+$('select[name="classroom"]').val()+"&date="+$('#date').val()+"&chatper="+$('input[name="chapter"]').val()+"&startTime="+$('#startTime').val()+"&endTime="+$('#endTime').val()+"&parentGrade="+$('select[name="parentGrade"]').val()+"&parentCategory="+$('select[name="parentCategory"]').val()+"&viewPassword="+$('input[name="viewPassword"]').val())
            avalon.vmodels[vm.livedialogID].toggle = true;
        }, 
        showAvaDialog:function(id){
            avalon.vmodels[id].toggle = true;
        },
        avalogon:function(id){
            $.ajax({
                url:'http://xy.ava.com.cn/lxx/j_spring_security_check',
                data:{
                    j_username:$('[name="ava_name"]').val(),
                    j_password:$('[name="ava_password"]').val(),
                    isAppLogon:1,
                    deviceType:5
                },
                type:'post',
                success:function(res){
                    if(res.status == 0){
                        vm.uri = 'AVA:'+(res.result&&res.result.userId);
                        vm.logon = 'avaLogon';
                        avalon.vmodels[vm.livedialogID].toggle = false;
                    }else{
                        alert(res.msg);
                    }
                },
                error:function(){
                    alert("出错！")
                }
            })
        },
        dialogOpts:{
            title:'QQ-登记',
            height:500,
            width:900,
            container:'liveRegister',
            onInit:function(elem, vmodel, options, vmodels){
                
                vm.livedialogID = elem.$id;
                console.log(elem.$id)
                console.log(elem, vmodel, options, vmodels)
            }

        },
        avaDialogOpts:{
            title:'AVA-登记',
            height:500,
            width:600,
            container:'liveRegister',
            onInit:function(elem, vmodel, options, vmodels){
                 console.log(elem.$id)
                console.log(elem, vmodel, options, vmodels)
            }
        },
        logout:function(){
            vm.zgbm = ''
            vm.uri = ''
            vm.logon = ''
            vm.nickname = ''
            clearCookie('avanickname')
            clearCookie('avazgbm')
            clearCookie('avauri')
        },
        stafflogon:function(){
            // if(vm.zgbm!=""){
            //     vm.logon = 'stafflogon'
            if($('input[name="zgbm"]').val()!=''){
                vm.logon = 'stafflogon'
                vm.nickname = "职工"+vm.zgbm
                setCookie('avanickname',vm.nickname)
                setCookie('avazgbm',$('input[name="zgbm"]').val())
            }else{
                alert('请输入教职工号');
            }
            $("#date").val(new Date().getFullYear()+'-'+(new Date().getMonth()+1)+'-'+new Date().getDate())
        },
        register: function() {
            if(vm.registering){
                vm.registering = true;
                return;
            }
            if(vm.$setting.enableQQAuth){
                if(vm.uri==''){
                    alert("请登录...");
                    return;
                }
            }
            // if(!vm.title)
            if(!$('input[name="title"]').val()){
                alert('标题不能为空！');
                return;
            }
            // if(!vm.speaker)
            if(!$('input[name="speaker"]').val()){
                alert('主讲人不能为空！');
                return;
            }
            if(!vm.date){
                alert('日期不能为空！');
                return;
            }
            if(!vm.chapterselect.startTimeTip){
                alert('直播时间不能为空！');
                return;
            }
            if(!vm.chapterselect.endTimeTip){
                alert('结束时间不能为空！');
                return;
            }
            // 结束时间不能小于开始时间
            var startTimeArr = vm.chapterselect.startTimeTip.split(':');
            var endTimeArr = vm.chapterselect.endTimeTip.split(':');
            if(startTimeArr[0]>endTimeArr[0]||(startTimeArr[0]==endTimeArr[0]&&startTimeArr[1]>=endTimeArr[1])){
                alert('结束时间必须大于开始时间');
                return;
            }
            if(vm.equipment==''||vm.equipment==' '||vm.equipment == -1){
                alert('课室不能为空！');
                return;
            } 

            api.getItems({
                method: api.setLiveItemAdd,
                query: {
                    //vm.title
                    title: $('input[name="title"]').val(),
                    // vm.speaker
                    speaker: $('input[name="speaker"]').val(),
                    startTime: vm.date +" " +vm.chapterselect.startTimeTip,
                    endTime: vm.date +" " +vm.chapterselect.endTimeTip,
                    parentGrade: vm.parentGrade,
                    parentCategory: vm.parentCategory,
                    parentRecordEquipment:vm.equipment,
                    viewPassword: vm.viewPassword,
                    chapter: vm.chapterselect.chapter,
                    ParentEmployee: vm.$setting.enableQQAuth?vm.uri:vm.zgbm,
                    
                }
            }, function(res) {
              if(res.success){
                alert("保存成功！");
                $('input[name="title"]').val('')
                $('input[name="speaker"]').val('')
                vm.equipment=' '
                vm.chapterselect.chapter=''
                vm.chapterselect.startTimeTip=''
                vm.chapterselect.endTimeTip=''
                avalon.router.go("myRegister",{})
              }else{
                vm.registering = false;
                alert(res.message)
              }
            })
        }
    });
    
    vm.$watch("setting", function(param) {
        vm.$setting = avalon.define(
            avalon.mix(vm.$setting, param))
    })
    // 判断选择日期是否周末
    vm.$watch("date",function(str){
        var d =new Date(str.replace(/\-/g,'/')).getDay();
        vm.selectDayIsWeekend =  (d==0||d==6);
        if(str==""){
            vm.data = new Date().getFullYear()+'-'+(new Date().getMonth()+1)+'-'+new Date().getDate();
        }
        console.log(vm.selectDayIsWeekend)
    })
    return avalon.controller(function($ctrl) {
        // 视图渲染后，意思是avalon.scan完成
        $ctrl.$onRendered = function() {
            $("#startTime").timepicker({
                "timeFormat": "HH:mm"
            })
            $("#endTime").timepicker({
                "timeFormat": "HH:mm"
            })
            $("#date").datepicker({
                "dateFormat": "yy-mm-dd"
            })
            if(!vm.data){
                vm.data = new Date().getFullYear()+'-'+(new Date().getMonth()+1)+'-'+new Date().getDate();
            }
            new Promise(function(res, rej) {
                res()
            }).then(function() {
                return api.getItems({
                    method: api.getGradeList,
                    handleData: false
                }, function(res) {
                    if (res.data) {
                        vm.gradeSection = _.merge([], res.data.gradeSection)
                    }
                })
            }).then(function() {
                return api.getItems({
                    method: api.getCategories,
                    handleData: false
                }, function(res) {

                    if (res.data) {
                        vm.categorySection = _.merge([], res.data.categorySection)
                    }
                })
            }).then(function() {
                // TODO 这里的接口没有排序
                return api.getItems({
                    method: api.getRecordeEquimentTimeList


                }, function(res) {
                    if (res.list) {


                        vm.timeList = _.merge([], res.list)
                    }
                })
            }).then(function(){
                return api.getItems({
                    method:api.getPubRecordEquipmentList
                },function(res) {
                    if(res.list){
                        vm.equipmentList = _.merge([],res.list)
                    }
                })
            })

        };
        // 进入视图
        $ctrl.$onEnter = function(param, rs, rj) {
            var tt = location.hash.replace(/\#\!/g, '')
            if(tt.indexOf('?')!=-1){
                var currentHash = tt.split('?')[1].split('&');
                console.log(currentHash)
                for(var i=0;i<currentHash.length;i++){
                    var attr = currentHash[i].split('=');
                    if(attr[0]=="authQQ"){
                        vm.logon = "QQLogon"
                    }else if(attr[0]=="code"){
                        if(attr[1]){

                            vm.uri = decodeURIComponent(attr[1])

                            setCookie('avauri',vm.uri)
                        }
                    }else if(attr[0]=="chapter"){
                        if(attr[1]){
                            vm.chapterselect.chapter = decodeURIComponent(attr[1])
                        }
                    }else if(attr[0]=="startTime"){
                        if(attr[1]){
                           vm.chapterselect.startTimeTip = decodeURIComponent(attr[1])
                            //$('#startTime').val(decodeURIComponent(attr[1]))
                        }
                    }else if(attr[0]=="endTime"){
                        if(attr[1]){
                            vm.chapterselect.endTimeTip = decodeURIComponent(attr[1])
                        }
                    }else if(attr[0]=="parentRecordEquipment"){
                        if(attr[1]){
                            vm.equipment = attr[1]
                        }
                    }else{

                        if(attr[1]){
                            vm[attr[0]] = decodeURIComponent(attr[1])
                        }
                    }
                    //console.log(i)
                }
                //console.log(vm)
                if(vm.nickname!=''){
                    setCookie('avanickname',vm.nickname)
                }
                location.hash = location.hash.split("?")[0]
                // vm.data = new Date().toLocaleDateString().replace(/\//g,'-');

            }

            // console.log(currentHash)
            if(param.itemID!=null){
                vm.equipment = param.itemID;
                vm.equipmentDefault = true;
            }
            // 获取登录状态
            if(getCookie('avazgbm')){
                vm.zgbm = getCookie('avazgbm')
                vm.logon = "stafflogon"
                
            }
            if(getCookie('avanickname')){
                vm.nickname = getCookie('avanickname')
            }
            if(getCookie('avauri')){
                vm.uri = getCookie('avauri')
                vm.logon = "QQLogon"
            }
            window.setValue = function(uri,nickname){
                console.log(top.window.avalon.vmodels[vm.livedialogID])
                if(!avalon.vmodels[vm.livedialogID]) {
                    console.log('fffffffff')
                    return;
                }
                vm.uri = uri;
                vm.logon = 'QQLogon';
                vm.nickname = nickname
                // setCookie('avazgbm',vm.zgbm)
                setCookie('avauri',vm.uri)
                setCookie('avanickname',vm.nickname)
                console.log(avalon.vmodels['livedialog'])
                avalon.vmodels[vm.livedialogID].toggle = false
               
                $("#date").val(new Date().getFullYear()+'-'+(new Date().getMonth()+1)+'-'+new Date().getDate())
            }
            Date.prototype.Format = function(fmt) { //author: meizz   
                var o = {
                    "M+": this.getMonth() + 1, //月份   
                    "d+": this.getDate(), //日   
                    "h+": this.getHours(), //小时   
                    "m+": this.getMinutes(), //分   
                    "s+": this.getSeconds(), //秒   
                    "q+": Math.floor((this.getMonth() + 3) / 3), //季度   
                    "S": this.getMilliseconds() //毫秒   
                };
                if (/(y+)/.test(fmt))
                    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
                for (var k in o)
                    if (new RegExp("(" + k + ")").test(fmt))
                        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                return fmt;
            }


        };
        // 对应的视图销毁前
        $ctrl.$onBeforeUnload = function() {
            vm.logon = ''
            vm.zgbm = ''
            vm.uri = ''
        };
        $ctrl.$vmodels = [vm];
    })
});
